package a08_回溯算法;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * a20_N皇后复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/1/6
 */
public class a20_N皇后复习1 {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        char[][] path = new char[n][n];
        for (int i = 0; i < path.length; i++) {
            for (int j = 0; j < path[i].length; j++) {
                path[i][j] = '.';
            }
        }
        traversal(result, path, n, 0);
        return result;
    }

    private void traversal(List<List<String>> result,
                           char[][] path,
                           int n,
                           int rowIdx){
        if (rowIdx == n) {
            result.add(pathToList(path));
            return;
        }
        for (int i = 0; i < path[rowIdx].length; i++) {
            if(!isValid(path,n,rowIdx,i)){
                continue;
            }
            path[rowIdx][i] = 'Q';
            traversal(result, path, n, rowIdx + 1);
            path[rowIdx][i] = '.';
        }
    }

    private boolean isValid(char[][] chars, int n, int rowIdx, int colIdx) {
        //列
        for (int i = 0; i < rowIdx; i++) {
            if(chars[i][colIdx] == 'Q'){
                return false;
            }
        }

        //45°
        for(int i=rowIdx-1,j=colIdx-1;i>=0&& j>=0;i--,j--){
            if(chars[i][j] == 'Q'){
                return false;
            }
        }

        //45°
        for(int i=rowIdx-1,j=colIdx+1;i>=0&& j<n;i--,j++){
            if(chars[i][j] == 'Q'){
                return false;
            }
        }

        return true;
    }

    private List<String> pathToList(char[][] path) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < path[i].length; j++) {
                sb.append(path[i][j]);
            }
            result.add(sb.toString());
        }
        return result;
    }
}
